package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    MinioClient minioClient;
    @Autowired
    MinioProperties minioProperties;
    @Override
    public String upload(MultipartFile file) {

        try {
            //判断桶是否存在
            boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());

            if(!b){
                //创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());

                //设置桶的权限
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(createBucketPolicyConfig(minioProperties.getBucketName())).build());



            }

            //文件的名字
            String fileName = file.getOriginalFilename();
            String suffixName= fileName.substring(fileName.lastIndexOf(".")); //.jpg
            String prefixName= UUID.randomUUID().toString();
            String newFileName=prefixName+suffixName;
            //上传文件
            minioClient.putObject(PutObjectArgs.builder().bucket(minioProperties.getBucketName()).contentType(file.getContentType()).object(newFileName).stream(file.getInputStream(),file.getSize(),-1).build());

            //String url=minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+newFileName;
            return String.join("/", minioProperties.getEndpoint(), minioProperties.getBucketName(), newFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }


    private String createBucketPolicyConfig(String bucketName) {

        return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
    }
}
